/**
 * 宽带预约列表
 */
(function($) {
  var pageData = {};
  var pageCount = 1;
  var filterType = 3;
  var pageNumber = 0;
  var groupList = new Array();
  var TYPE_VNET = "vnet";
  var TYPE_OPPONENT = "opponent";
  var TYPE_OPPORTUNITY = "opportunity";
  var TYPE_CAMPUS_V = "campus_v";
  var itemClickObject;

  /*
  封装参数
  */
  var getMyParams = function(group_no, group_name) {
    var params = "?";
    var myParam = getParams();
    if (myParam) {
      params += myParam;
      if (group_no) {
        params += "&";
      }
    }
    if (group_no) {
      params += "group_no=" + group_no;
    }
    if (group_name) {
      params += "&group_name=" + group_name;
    }

    return params;
  };

  var bind = function(object, clickFunc) {
    itemOnClick(object, clickFunc);
  };

  var itemOnClick = function(object, clickFunc) {
    $(object).off("click"); //取消li事件
    /*li事件*/
    $(object).on("click", function() {
      var $siblingsNode = $(this).siblings();
      var primaryClass = "select-item";
      var defaultColor = "#fff";
      var selectColor = "#0c79b1";

      if ($siblingsNode.hasClass(primaryClass)) {
        $siblingsNode.removeClass(primaryClass);
        $siblingsNode.css("background-color", defaultColor);
      }
      if ($(this).hasClass(primaryClass)) {
        $(this).removeClass(primaryClass);
        $(this).css("background-color", defaultColor);
      } else {
        $(this).addClass(primaryClass);
        $(this).css("background-color", selectColor);
      }
      clickFunc(this);
      event.stopPropagation();
      itemClickObject = this;
      setTimeout(changeItemClickBackgroud, 1000);
    });
  };

  var changeItemClickBackgroud = function() {
    var $siblingsNode = $(itemClickObject).siblings();
    var primaryClass = "select-item";
    var defaultColor = "#fff";
    var selectColor = "#0c79b1";

    if ($siblingsNode.hasClass(primaryClass)) {
      $siblingsNode.removeClass(primaryClass);
      $siblingsNode.css("background-color", defaultColor);
    }
    if ($(itemClickObject).hasClass(primaryClass)) {
      $(itemClickObject).removeClass(primaryClass);
      $(itemClickObject).css("background-color", defaultColor);
    } else {
      $(itemClickObject).addClass(primaryClass);
      $(itemClickObject).css("background-color", selectColor);
    }
  }


  var getVcodeCallBack = function(outData) {
    if (!outData) {
      $("#alert-content").html("V网数据为空！");
      $("#group-alert").modal('open');
      return;
    }
    console.info(outData);
    if (outData.VGRP_INFO == null) {
      $("#alert-content").html("获取V网编码失败：查无V网");
      $("#group-alert").modal('open');
      return;
    }
    window.location.href = 'vnet.html?' + getParams() + "&vcode=" + outData.VGRP_INFO.VGRP_NO + "&vname=" + outData.VGRP_INFO.VGRP_NAME + "&groupId=" + curGroupId;
  };

  var getVcode = function(groupId) {
    curGroupId = groupId;
    //TODO: 去掉PHONE_NO
    var params = {
      "BODY": {
        "PHONE_NO": getMobile(),
        "WORN_SERV_CODE": "sEsopVGroupNo",
        "LOGIN_NO": getEmpCode(),
        "UNIT_ID": groupId,
        "COMMON_INFO": {
          "PROVINCE_GROUP": "10008"
        }
      }
    };
    sendRestPostAjax(params, Constants.rpcCrmHost + "sUserOrdQry?token=" + getToken(), getVcodeCallBack);
  };
  
/*  var getCampusVcodeCallBack = function(outData) {
	    if (!outData) {
	      $("#alert-content").html("V网数据为空！");
	      $("#group-alert").modal('open');
	      return;
	    }
	    console.info(outData);
        if (outData.VGRP_INFO == null) {
	      $("#alert-content").html("获取V网编码失败：查无V网");
	      $("#group-alert").modal('open');
	      return;
	     }
	    window.location.href = '../../campus/vnet.html?' + getParams() + "&vcode=" + outData.VGRP_INFO.VGRP_NO + "&groupId=" + curGroupId;
	  };
  
  var getCampusVcode = function(groupId) {
	    curGroupId = groupId;
	    //TODO: 去掉PHONE_NO
	    var params = {
	      "BODY": {
	        "PHONE_NO": getMobile(),
	        "WORN_SERV_CODE": "sEsopVGroupNo",
	        "LOGIN_NO": getEmpCode(),
	        "UNIT_ID": groupId,
	        "COMMON_INFO": {
	          "PROVINCE_GROUP": "10008"
	        }
	      }
	    };
	    sendRestPostAjax(params, Constants.rpcCrmHost + "sUserOrdQry?token=" + getToken(), getCampusVcodeCallBack);
	  };
*/
  
  var getCampusVcodeCallBack = function(groupId,grpName,outData) {
	    if (!outData) {
	      $("#alert-content").html("V网数据为空！");
	      $("#group-alert").modal('open');
	      return;
	    }
	    console.info(outData);
      if (outData.VGRP_INFO == null) {
	      $("#alert-content").html("查无V网");
	      $("#group-alert").modal('open');
	      return;
	     }
	    //window.location.href = '../../campus/vnet/vnet.html?' + getParams() + "&vcode=" + outData.VGRP_INFO.VGRP_NO + "&groupId=" + groupId+"&grpName="+encodeURI(grpName);
	    window.location.href = "../../campus/vnet/vnet.html" + getMyParams(groupId, grpName);
	  };
  
  var getCampusVcode = function(groupId,grpName){
	  var params = {
	  	      "BODY": {
	  	        "PHONE_NO": getMobile(),
	  	        "WORN_SERV_CODE": "sEsopVGroupNo",
	  	        "LOGIN_NO": getEmpCode(),
	  	        "UNIT_ID": groupId,
	  	        "COMMON_INFO": {
	  	          "PROVINCE_GROUP": "10008"
	  	        }
	  	      }
	  	    };
	  console.log("request params = "+JSON.stringify(params));
	  $.ajax({
	    type: "post",
	    contentType: "application/json",
	    data: JSON.stringify(params),
	    url:  Constants.rpcCrmHost + "sUserOrdQry?token=" + getToken(),
	    dataType: "json",
	    async: true,
	    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
	      console.log("data = "+JSON.stringify(data));
	      var returnData = data.ROOT;
	      console.info(returnData);
	      
	      if(returnData.RETURN_CODE!=0){
	        alert(returnData.RETURN_MSG);
	        console.log("获取RPC接口返回失败！code:"+returnData.RETURN_CODE);
	        return;
	      }
	      
	      getCampusVcodeCallBack(groupId,grpName,returnData.OUT_DATA);
	    },
	    error : function(textStatus) {
	      alert("网络或服务器异常，请稍后再试！");
	      console.info("request error:");
	    }
	  });
	};


  var goByType = function(object) {
    var groupID = $(object).find("input[name='group_id']").val();
    var groupName = $(object).find("div[name='group_name']").html();
    var mgrName = $(object).find("input[name='mgrName']").val();
    var mgrEmpCode = $(object).find("input[name='mgrEmpCode']").val();
    $("#group_id").val(groupID);
    $("#group_name").val(groupName);
    //$('#my-alert').modal('close');
    var params = getParams() + '&grpId=' + groupID + '&mgrName=' + mgrName + '&mgrEmpCode=' + mgrEmpCode + '&grpName=' + groupName;
    var type = getParamValue('type');
    if (type == TYPE_VNET) {
      //V网
      getVcode(groupID);
    } else if (type == TYPE_CAMPUS_V) {
        //校园V网
    	//alert("进入校园V网");
    	getCampusVcode(groupID,groupName);
    	//window.location.href = "../../campus/vnet/vnet.html" + getMyParams(groupID, groupName);
    } else if (type == TYPE_OPPONENT) {
      window.location.href = "../esop/opponent_list.html" + getMyParams(groupID, groupName);
    } else if (type == TYPE_OPPORTUNITY) {
      window.location.href = "../esop_demo/opportunity.html?" + params;
    } else {
      //集团信息查询
      if (getParamValue("EmpCode") == "aaaX27") { //DEMO
        window.location.href = "../esop_demo/group_details.html?" + params;
      } else {
        window.location.href = "group_details.html?" + params;
      }
    }

  };


  var groupClickFunc = function(object) {
    goByType(object);
  }

  /*
  显示数据
  */
  var showGroupData = function(data) {
    if (data.groupInfoList instanceof Array) {
      list = data.groupInfoList;
      for (var i = 0; i < list.length; i++) {
        groupList.push(list[i]);
      }
    } else if (data.groupInfoList instanceof Object) {
      if (data.groupInfoList.empty == undefined) {
        groupList.push(data.groupInfoList);
      }
    }
    var $tpl = $('#amz-group-list');
    var source = $tpl.text();
    var template = Handlebars.compile(source);
    var myData = {
      list: groupList,
      "error": "没有集团信息"
    };

    $("#group-list").children('li').remove();
    $("#group-list").children('div').remove();

    var html = template(myData);
    $tpl.before(html);
    bind("#group-list > li", groupClickFunc);
  };

  var isDigital = function(keyword) {
    var reg = /^[0-9]*$/;
    if (reg.test(keyword)) {
      return true;
    }
    return false;
  }

  var buildQueryGroupParams = function(pageNumber, keyword) {
    var url = "grpName=";
    if (isDigital(keyword)) {
      url = url + "&grpNo=" + keyword + "&serviceNo=&pageStart=" + pageNumber * 30 + "&pageLimit=30";
    } else {
      url = url + encodeURI(keyword) + "&grpNo=" + "&serviceNo=&pageStart=" + pageNumber * 30 + "&pageLimit=30";
    }

    params = {
      "token": getParamValue("token"),
      "staffNo": getParamValue("EmpCode"),
      "passUrl": url
    };
    console.log("request:" + JSON.stringify(params));
    return params;
  }

  var loadGroupData = function(pageNumber) {
    showLoadingBar($("#loadingbar"), true);
    var keyword = $("#keyword").val();
    params = buildQueryGroupParams(pageNumber, keyword);

    $.ajax({
      type: "post",
      contentType: "application/json",
      data: JSON.stringify(params),
      url: Constants.rpcEsopHost + "queryGrouInfo",
      dataType: "json",
      async: true,
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        showLoadingBar($("#loadingbar"), false);
        console.log("data = " + data);
        pageData = data.return;
        console.info(data.return);
        if (data.rtnCode != 1000) {
          // showBottomMsg(data.rtnMsg);
          alert(data.rtnMsg);
          console.log("获取RPC接口返回失败！code:" + data.rtnCode);
          return;
        }
        if (data.return.resultCode != "00") {
          alert(data.return.resultCode);
          console.log("获取信息接口返回失败！code:" + data.return.resultCode);
          return;
        }
        showGroupData(data.return);
      },
      error: function(textStatus) {
        showLoadingBar($('#loadingbar'), false);
        alert("网络或服务器异常，请稍后再试！");
        console.info("request error:");
      }
    });
  };

  var initTitle = function() {
    var t = getParamValue("type");
    if (t == TYPE_VNET) {
      //V网
      document.title = "V网成员管理";
      
    } else if (t == TYPE_CAMPUS_V) {
      document.title = "校园V网";
    } else if (t == TYPE_OPPONENT) {
      document.title = "对手信息管理";
    } else if (t == TYPE_OPPORTUNITY) {
      document.title = "商机管理";
    } else {
      //集团信息查询
      document.title = "集团信息查询";
    }
  };

  $(function() {
    initTitle();
    /*滚动条*/
    var $doc = $(document);
    $doc.scroll(function() {
      console.log("height = " + ($doc.height() - $(window).height()));
      console.log("scrollTop = " + Math.ceil($doc.scrollTop()));
      console.log("Math.ceil($doc.scrollTop()) = " + Math.ceil($doc.scrollTop()));
      if (Math.ceil($doc.scrollTop()) >= ($doc.height() - $(window).height())) {
        var $msg = $("#no-data-msg");
        console.log("debug 1");
        if (!$.isEmptyObject(pageData)) {
          console.log("debug 2");
          if (!$msg.hasClass("am-hide")) {
            console.log("debug 3");
            $msg.addClass("am-hide");
          }
          console.log("pageNumber=" + pageNumber);
          pageNumber++;
          loadGroupData(pageNumber);
        } else {
          console.log("debug 5");
          if ($msg.hasClass("am-hide")) {
            console.log("debug 6");
            $msg.removeClass("am-hide");
          }
        }
      }
    });

    $("#search_button").on("click", function() {
      groupList = [];
      loadGroupData(pageNumber);
    });
  });
})(jQuery);